<?php

namespace app\modules\Cost\models;

use Yii;
use app\modules\Supplier\models\Supplier;
use app\modules\Product\models\Product;
use app\modules\Manage\models\User;
use yii\web\UploadedFile;

/**
 * This is the model class for table "cost".
 *
 * @property int $id
 * @property int $product_id 团队ID
 * @property int $cost_type 成本项类型
 * @property int $supplier_id 供应商ID
 * @property int $payment 支付方式
 * @property int $day_num 间夜
 * @property int $currency 货币(美元)
 * @property string $price 成本
 * @property int $status 1正常  2 禁用 
 * @property int $user_id 创建人ID
 * @property string $created_at 创建时间
 * @property string $updated_at
 */
class Cost extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'cost';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['product_id', 'cost_type', 'supplier_id', 'payment', 'day_num', 'currency', 'status', 'user_id','confirm','comfirm_id'], 'integer'],
            [['price'], 'number'],
            [['supplier_id','price'],'required'],
            [['created_at','payment_time','updated_at','comfirm_at'], 'safe'],
            [['remark'], 'string', 'max' => 1024],
            [['file_path','file_name'], 'string', 'max' => 256],
            [['file_size','file_ext'], 'string', 'max' => 64],
            ['day_num','validateDayNum','skipOnEmpty' => false, 'skipOnError' => false],
            ['price','validatePrice','skipOnEmpty' => false, 'skipOnError' => false],
        ];
    }

    public function validateDayNum()
    {
        if($this->supplier_id){
            $model = Supplier::findOne($this->supplier_id);
            if($model){
                if($model->type == 1){
                    if(empty($this->day_num)){
                        $this->addError('day_num', '间夜不能为空!');
                    }
                }
            }
        }
    }

    public function validatePrice()
    {
       
        if(empty($this->price)){
            $this->addError('price', '金额不能为空');
        }
        
        $product = Product::findOne($this->product_id);
        
        if ($this->price > $product->surPrice) {
            $this->addError('price', '金额不能大于剩余成本项金额');
        }
     
    }

     // 保存前处理
    public function beforeSave($insert) {//{{{

        //附件
        $upload = UploadedFile::getInstance($this, "file_path");

        if($upload){
            $dir = sprintf("uploads/cost/%s",date("Ym"));
            if(!is_readable($dir)) {
                is_file($dir) or mkdir($dir,0755);
            }
            $name = $upload->name;
            $size = $upload->size; 
            $suffix = $upload->extension;
            $path = sprintf('%s/%s.%s', $dir, uniqid(true), $suffix);
            $ret = $upload->saveAs($path);
            if($ret){
                $this->file_path = $path;
                $this->file_ext = $suffix;
                $this->file_name = $name;
                $this->file_size = $size;
            }
        }else{
            unset($this->file_path);
        }

        if($insert){
            $this->created_at = date("Y-m-d H:i:s");
            $this->user_id    = Yii::$app->user->id;
            $this->status = 1;
        }
        
        return parent::beforeSave($insert);
    }//}}}

    //获取间夜
    public function getDayNum(){
        return ($this->day_num == 0) ? ' / ' : $this->day_num;
    }


    //  获取供应商信息
    public function getSupplier(){
        return $this->hasOne(Supplier::className(), ['id' => 'supplier_id']);
    }

     //  获取团队信息
    public function getProduct(){
        return $this->hasOne(Product::className(), ['id' => 'product_id']);
    }

     //获取销售（开团人）
    public function getUserName(){
        $user = User::findOne($this->user_id);
        return $user ? $user->name : ' ';
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'product_id' => Yii::t('app', 'Product ID'),
            'cost_type' => Yii::t('app.cost', 'Cost Type'),
            'supplier_id' => Yii::t('app.cost', 'Supplier ID'),
            'payment' => Yii::t('app.cost', 'Payment'),
            'day_num' => Yii::t('app.cost', 'Day Num'),
            'currency' => Yii::t('app', 'Currency'),
            'price' => Yii::t('app.cost', 'Price'),
            'remark' => Yii::t('app.cost', 'Remark'),
            'payment_time' => Yii::t('app.cost', 'Payment Time'),
            'status' => Yii::t('app', 'Status'),
            'confirm' => Yii::t('app.cost', 'Confirm'),
            'comfirm_id' => Yii::t('app.cost', 'Confirm ID'),
            'comfirm_at' => Yii::t('app.cost', 'Confirm At'),
            'user_id' => Yii::t('app', 'User ID'),
            'created_at' => Yii::t('app', 'Created At'),
            'updated_at' => Yii::t('app', 'Updated At'),
        ];
    }
}
